<template>
  <layout-card :filters="exampleOptions" headline="物品类型管理" @search-change="searchChange" @search-reset="searchReset">
    <template #action>
      <el-button type="primary" @click="() => openAddDialog()">新增</el-button>
      <el-button type="primary" @click="handleExport">导出</el-button>
    </template>
    <table-common :columns="exampleColumns" :loading="loading" :pagination="pager" :table-data="tableData" size="large"
      @current-change="currentChange" @size-change="sizeChange">
      <template #index="{ row }">
        {{ row.creator && row.creator.name || '' }}
      </template>
      <template #user="{ row }">
        {{ row.creator && row.creator.name || '' }}
      </template>
      <template #classifyCode="{ row }">
        {{ renderclassifyCodeLabel(row.classifyCode) }}
      </template>
      <template #timeLimit="{ row }">
        {{ row.timeLimit }}
        {{ row.timeLimitUnit === 'H' ? '小时' : '' }}
        {{ row.timeLimitUnit === 'M' ? '月' : '' }}
        {{ row.timeLimitUnit === 'D' ? '天' : '' }}
        {{ row.timeLimitUnit === 'Y' ? '年' : '' }}
      </template>
      <template #action="{ row }">
        <el-button class="link-btn" link type="primary" @click="() => openUpdateDialog(row)">编辑</el-button>
        <el-popconfirm title="是否删除?" confirmButtonText="确定" cancelButtonText="取消" @confirm="() => handleDelete(row)">
          <template #reference>
            <el-button class="link-btn" link type="danger">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </table-common>
  </layout-card>

  <Edit :visible="centerDialogVisible" :info="info" @cancel="handleCancel" @ok="handleOk" />
</template>

<script lang="ts" setup>
import dayjs from 'dayjs';
import { ref, reactive, onBeforeMount, computed, watch, toRaw } from 'vue'
import { useStore } from 'vuex'
import LayoutCard from '@/components/LayoutCard/index.vue'
import type { TabsPaneContext } from 'element-plus'
import TableCommon from '@/components/TableCommon/index.vue'
import { exampleColumns } from './config/columns'
import { goodsTypePageList, goodsTypeDelete, goodsTypeExportXls } from '@/api/lose/goodsType'
import type { PageListType } from '@/api/lose/goodsType'
import { image } from '@/assets/index'
import { ElMessage } from 'element-plus'
import Edit from './edit.vue'

interface SearchType {
  startTime?: String;
  endTime?: String[];
  goodsType?: String;
  classifyCode?: String;
}

interface GoodsTypeState {
  typeId: string;
  goodsType: string;
  classifyCode: string;
  timeLimit: string;
  timeLimitUnit: string;
  remarks: string;
}

const store = useStore()
// 新增弹窗是否打开
const centerDialogVisible = ref(false)
const loading = ref(false)
const tableData = ref<GoodsTypeState[]>([])
const userInfo = computed(() => store.state.user.userInfo)
const goodsClassifyList = computed(() => store.state.goodsType.loseGoodsClassify)
const info = ref(null)
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

/**
* 6.打开编辑弹框
*/
const openAddDialog = (row = null) => {
  console.log(row)
  centerDialogVisible.value = true
  info.value = row
}
/**
* 点击新增方法
*/
const openUpdateDialog = (row = null) => {
  console.log(row)
  centerDialogVisible.value = true
  info.value = row
}

// 删除
const handleDelete = async (row: GoodsTypeState) => {
  const res: any = await goodsTypeDelete({
    typeId: `${row.typeId}`, mender: {
      id: userInfo.value.userId,
      name: userInfo.value.name,
      userName: userInfo.value.userName,
      organId: userInfo.value.organId || '',
      organName: userInfo.value.organName || ''
    }
  });
  if (res?.code === '1') {
    if (tableData.value.length === 0) {
      pager.currentPage = 1
    }
    loadData()
    ElMessage.success('已删除！')
  } else {
    ElMessage.error(res?.message || '删除失败，请重试！')
  }
}

/**
* 弹窗点击取消
*/
const handleCancel = () => {
  centerDialogVisible.value = false
}

/**
* 弹窗点击确认
*/
const handleOk = () => {
  centerDialogVisible.value = false
  loadData()
}

// 分页
const sizeChange = (size: number) => {
  pager.pageSize = size
  loadData()
}

const currentChange = (value: number) => {
  pager.currentPage = value
  loadData()
}
// 查询条件
const exampleOptions = ref([
  {
    label: '分类',
    prop: 'classifyCode',
    type: 'select',
    defaultValue: '',
    inputProps: {
      options: [
        { label: '全部', value: '' },
      ]
    }
  },
  {
    label: '物品类型',
    prop: 'goodsType',
    type: 'input',
    inputProps: {
      clearable: true,
      placeholder: '请输入分类名称'
    }
  },
  {
    label: '时间',
    prop: 'endTime',
    type: 'datePicker',
    defaultValue: [],
    inputProps: {
      type: 'daterange',
      'value-format': 'YYYY-MM-DD HH:ss:mm'
    }
  }
])
const search = ref<SearchType>({})
const loadData = async () => {
  loading.value = true
  const payload: PageListType = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: {
      isDisable: "N",
    }
  }
  if (search.value.endTime && search.value.endTime?.length > 0) {
    payload.condition.timeStart = search.value.endTime[0] || '';
    payload.condition.timeEnd = search.value.endTime[1] || '' ? dayjs(search.value.endTime[1] || '').format('YYYY-MM-DD 23:59:59') : '';
  }
  if (search.value.classifyCode) {
    payload.condition.classifyCode = search.value.classifyCode || '';
  }
  if (search.value.goodsType) {
    payload.condition.goodsType = search.value.goodsType || '';
  }
  // ...获取数据
  const res = await goodsTypePageList(payload);
  loading.value = false
  if (res && res.code === '1') {
    tableData.value = res?.data?.list?.map(item => ({ ...item, createTime: dayjs(item.createTime).format('YYYY-MM-DD HH:ss:mm') }))
    pager.total = res?.data?.total
  } else {
    ElMessage.error(res?.message || '获取列表失败，请刷新重试！')
  }
}

/**
* 点击查询
*/
const searchChange = (data: FilterDataType) => {
  search.value = data
  loadData()
}

/**
* 点击重置
* @param data 数据
*/
const searchReset = (data: FilterDataType) => {
  search.value = data
  pager.currentPage = 1
  pager.pageSize = 10
  loadData()
}
const handleExport = async () => {
  
  if (tableData.value.length === 0) {
    ElMessage.error('暂无数据！')
    return;
  }
  const payload: any = {
  }
  if (search.value.endTime && search.value.endTime?.length > 0) {
    payload.timeStart = search.value.endTime[0] || '';
    payload.timeEnd = search.value.endTime[1] || '';
  }
  if (search.value.classifyCode) {
    payload.classifyCode = search.value.classifyCode || '';
  }
  if (search.value.goodsType) {
    payload.goodsType = search.value.goodsType || '';
  }
  // ...获取数据
  const res: any = await goodsTypeExportXls(payload);

  const link = document.createElement("a");
  const blob = new Blob([res], { type: "application/vnd.ms-excel" });
  link.style.display = "none";
  link.href = URL.createObjectURL(blob);
  link.setAttribute("download", `物品类型${dayjs().format('YYYY-MM-DD')}.xlsx`);  //报表名称可自定义
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

const renderclassifyCodeLabel = (key: string) => {
  let name = ''
  goodsClassifyList.value.forEach((item: { value: string; label: string }) => {
    if (item.value === key) {
      name = item.label;
    }
  })
  return name;
}

const loadDict = () => {
  store.dispatch('goodsType/getDict')
}

onBeforeMount(() => {
  loadData();

  loadDict();
})

watch(() => goodsClassifyList.value, (val) => {
  console.log(toRaw(val))
  exampleOptions.value[0].inputProps.options = [{ label: '全部', value: '' }, ...toRaw(val)];
})
</script>

<style lang="less" scoped>
@import url("./index.less");
</style>
